package com.fowo.api.sys.component;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.sys.entity.SysLog;
import com.fowo.api.sys.model.SysLogData;
import com.fowo.api.sys.service.SysLogService;
import org.springframework.context.ApplicationContext;

import java.util.Date;

/**
 * 日志数据写入代理
 */
public class SysLogWriter extends AppenderBase<ILoggingEvent> {

    private SysLogService sysLogService;

    @Override
    protected void append(ILoggingEvent eventObject) {
        if (sysLogService == null) {
            final ApplicationContext applicationContext = ContextHolder.getApplicationContext();
            if (applicationContext != null) {
                sysLogService = applicationContext.getBean(SysLogService.class);
            }
        }
        if (sysLogService == null) {
            return;
        }
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date(eventObject.getTimeStamp()));
        String formattedMessage = eventObject.getFormattedMessage();
        boolean isMessageCut = false;
        // 超长消息切断
        if (formattedMessage != null && formattedMessage.length() > 2000) {
            isMessageCut = true;
            formattedMessage = formattedMessage.substring(0, 1997) + "...";
        }
        sysLog.setFormattedMessage(formattedMessage);
        sysLog.setLevel(eventObject.getLevel().levelStr);
        sysLog.setSource(eventObject.getLoggerName());

        SysLogData data = new SysLogData();
        if (isMessageCut) {
            data.setMessage(eventObject.getFormattedMessage());
        }
        data.setArgumentArray(eventObject.getArgumentArray());
        if(eventObject.getThrowableProxy() != null) {
            data.setStackTraces(eventObject.getThrowableProxy().getStackTraceElementProxyArray());
        }
        sysLog.setData(data);
        try {
            sysLogService.create(sysLog);
        } catch (Exception e) {
            // 忽略写系统日志时发生的任何错误，不然会造成系统日志循环问题
        }
    }
}
